/**
 * 通用方法封装处理
 * Copyright (c) 2018 ruoyi
 */
// var ftp_url = "http://www.iyusheng.cn";
var ftp_url = "http://localhost:9060";
$(function(){
    // 复选框事件绑定
    if ($.fn.select2 !== undefined) {
        $("select.form-control:not(.noselect2)").each(function () {
            $(this).select2().on("change", function () {
                $(this).valid();
            })
        })
    }
    if ($(".i-checks").length > 0) {
        $(".i-checks").iCheck({
            checkboxClass: "icheckbox_square-green",
            radioClass: "iradio_square-green",
        })
    }
    if ($(".time").length > 0) {
        layui.use('laydate', function() {
            var laydate = layui.laydate;
            laydate.render({ elem: '#startTime', theme: 'molv' });
            laydate.render({ elem: '#endTime', theme: 'molv' });
            laydate.render({ elem: '#startTime1', theme: 'molv' });
            laydate.render({ elem: '#endTime1', theme: 'molv' });
            laydate.render({ elem: '#startTime2', theme: 'molv' });
            laydate.render({ elem: '#endTime2', theme: 'molv' });
        });
    }
});

/** 创建选项卡 */
function createMenuItem(dataUrl, menuName) {
    dataIndex = $.common.random(1,100),
        flag = true;
    if (dataUrl == undefined || $.trim(dataUrl).length == 0) return false;
    var topWindow = $(window.parent.document);
    // 选项卡菜单已存在
    $('.menuTab', topWindow).each(function() {
        if ($(this).data('id') == dataUrl) {
            if (!$(this).hasClass('active')) {
                $(this).addClass('active').siblings('.menuTab').removeClass('active');
                $('.page-tabs-content').animate({ marginLeft: ""}, "fast");
                // 显示tab对应的内容区
                $('.mainContent .RuoYi_iframe', topWindow).each(function() {
                    if ($(this).data('id') == dataUrl) {
                        $(this).show().siblings('.RuoYi_iframe').hide();
                        return false;
                    }
                });
            }
            flag = false;
            return false;
        }
    });
    // 选项卡菜单不存在
    if (flag) {
        var str = '<a href="javascript:;" class="active menuTab" data-id="' + dataUrl + '">' + menuName + ' <i class="fa fa-times-circle"></i></a>';
        $('.menuTab', topWindow).removeClass('active');

        // 添加选项卡对应的iframe
        var str1 = '<iframe class="RuoYi_iframe" name="iframe' + dataIndex + '" width="100%" height="100%" src="' + dataUrl + '" frameborder="0" data-id="' + dataUrl + '" seamless></iframe>';
        $('.mainContent', topWindow).find('iframe.RuoYi_iframe').hide().parents('.mainContent').append(str1);

        // 添加选项卡
        $('.menuTabs .page-tabs-content', topWindow).append(str);
    }
    return false;
}

/** 设置全局ajax超时处理 */
$.ajaxSetup({
    complete: function(XMLHttpRequest, textStatus) {
        if (textStatus == "parsererror") {
            $.modal.confirm("Login timeout! Please login again!", function() {
                window.location.href = ctx + "login";
            })
        }
    }
});

function objIsNull(obj){
    if(obj == null || obj === "" || obj == undefined || obj == 'undefined' ){
        return false;
    }
    return true;
}
/*下载*/
$('body').on('click', '.down', function () {
    var path = $(this).attr('data-text');
    form = $('<form></form>');
    form.attr('action', '/module/ordersHead/down');
    form.attr('method', 'post');
    input = $("<input type='hidden' name='fileUrl' />")
    input.attr('value', path);
    form.append(input);
    form.appendTo("body")
    form.css('display', 'none')
    form.submit();
});

//bootstrap-table 计算列合计行调用方法
function calculateLineTotal(value,property) {//(function中的value,"列字段的字符串")
    var count = 0;
    for (var i in value) {
        count = Calc.Add(value[i][property],count);
    }
    return count==0?'0':count;
}

function calculateLineTotalAsServer(value,property) {//(function中的value,"列字段的字符串")
    if (value.length != 0){
        return property;
    }
}

/*去除表格滚动条，添加页脚滚动条
同步页脚与表格滚动条的操作*/
function scynScroll() {
    //隐藏表格滚动条，显示页脚合计行滚动条
    /*$('.fixed-table-body').css("overflow-x","hidden");
    $('.fixed-table-footer').css("overflow","scroll");*/

    //监听滚动条 表格滚动与页脚合计行同步
    $('.fixed-table-body').scroll( function() {
        $('.fixed-table-footer').scrollTop($(this).scrollTop());
        $('.fixed-table-footer').scrollLeft($(this).scrollLeft());
        //滚动 使弹出框消失 bug：弹出框不随着滚动条滚动
        $("[data-toggle='popover']").popover('hide');
    });
    /*$('.fixed-table-footer').scroll( function() {
        $('.fixed-table-body').scrollTop($(this).scrollTop());
        $('.fixed-table-body').scrollLeft($(this).scrollLeft());
    });*/
}

/*展开折叠搜索框*/
$(".flex-botton").click(function () {
    var isExpanded =  $(this).attr("aria-expanded");
    if (isExpanded=="false"){
        $(this).children().text("foldSearch");
        $(this).children().attr('class',"glyphicon glyphicon-chevron-up");
    }else if(isExpanded=="true"){
        $(this).children().text("unfoldSearch");
        $(this).children().attr('class',"glyphicon glyphicon-chevron-down");
    }else{
        $(this).children().text("foldSearch");
        $(this).children().attr('class',"glyphicon glyphicon-chevron-up");
    }
})

/*清空搜索框中所有输入框的值*/
$(".reset-booton").click(function () {
    $(".reset").val('');//清空输入框
    $(".reset_select option:first").prop("selected", 'selected');//还原下拉框为初值
})

/*根据列名称拿选中的 */
function getBootstrapTableValueAsRow (name,rowid) {
    var reName = '';
    var rows = $('#bootstrap-table').bootstrapTable('getSelections');
    for (var key in rows) {
        var row = rows[key]
        reName = reName +(row[name]) + ","
    }
    return reName;
}

/*表头列拖动*/
function columnReSizable() {
    $("#bootstrap-table").colResizable({
        liveDrag : true ,
        gripInnerHtml : "<div class ='grip'></div>" ,
        draggingClass : "dragging" ,
        resizeMode : 'overflow',
    });
}


/*根据列名称拿所有的*/
function getBootstrapTableValue (name) {
    var reName = new Array();
    var rows = $('#bootstrap-table').bootstrapTable('getData');
    for (var key in rows) {
        var row = rows[key]
        reName.push(row[name])
    }
    return reName;
}

/*table id不確定的拿*/
function getBootstrapTableValueAsTwo (name,tablename) {
    var reName = new Array();
    var rows = $(tablename).bootstrapTable('getData');
    for (var key in rows) {
        var row = rows[key]
        reName.push(row[name])
    }
    return reName;
}
/*初始化打开图片插件*/
function  initialize_image() {

    $("body").append("<div id=\"blueimp-gallery\" class=\"blueimp-gallery\">\n" +
        "        <div class=\"slides\"></div>\n" +
        "        <h3 class=\"title\"></h3>\n" +
        "        <a class=\"prev\">‹</a>\n" +
        "        <a class=\"next\">›</a>\n" +
        "        <a class=\"close\">×</a>\n" +
        "        <a class=\"play-pause\"></a>\n" +
        "        <ol class=\"indicator\"></ol>\n" +
        "    </div>")

    $("#image_links").onclick = function (event) {
        event = event || window.event;
        var target = event.target || event.srcElement,
            link = target.src ? target.parentNode : target,
            options = {index: link, event: event},
            links = this.getElementsByTagName('a');
        blueimp.Gallery(links, options);
    };
}

function  initialize_image2() {
    $("#image_links1").onclick = function (event) {
        event = event || window.event;
        var target = event.target || event.srcElement,
            link = target.src ? target.parentNode : target,
            options = {index: link, event: event},
            links = this.getElementsByTagName('a');
        blueimp.Gallery(links, options);
    };
}
/*初始化提示框方法*/
function initialize_popover () {
    document.querySelector(".fixed-table-body").addEventListener("scroll", function(){
        $("[data-toggle='popover']").popover('hide');
    });
    $("[data-toggle='popover']").popover();
}

/*截取字符串*/
function sub_hidden (str) {
    var sub_num = 6;

    if (str == null){
        return '-';
    }
    if ( str.length > sub_num){
        return str.substring(0,sub_num) + "..";
    }else{
        return  str;
    }

}

/*去除空的数组*/
function trimNull(array) {
    for (var i = 0; i < array.length; i++) {
        if (array[i] == "" || typeof(array[i]) == "undefined") {
            array.splice(i, 1);
            i = i - 1;
        }
    }
    return array;
}

//gund滚动条滚动的时候调整表格高度
$(window).resize(function() {
    $('.fixed-table-body').css("height","calc(73vh)");
});

/*縮放事件*/
$(window).resize(function () {
    $('.fixed-table-body').css("height", "calc(73vh)");
});

/*建立webscoket连接,消息处理为重载页面*/
function webscoketRefresh(tips){
    var websocket;
    if ('WebSocket' in window) {
        websocket = new WebSocket("ws://www.iyusheng.cn/ws");
        // websocket = new WebSocket("ws://www.iyusheng.cn/ws");
    } else if ('MozWebSocket' in window) {
        websocket = new MozWebSocket("ws://www.iyusheng.cn/ws");
        // websocket = new MozWebSocket("ws://www.iyusheng.cn/ws");
    } else {
        websocket = new SockJS("http://www.iyusheng.cn/sockjs");
        // websocket = new SockJS("http://www.iyusheng.cn/sockjs");
    }
    websocket.onopen = function(event) {
        // console.log(event);
    };
    websocket.onmessage = function(event) {//接收消息回调
        // alert("您收到了消息！");
        $.modal.confirm(tips, function() {
            window.location.reload();
        });
    };
    websocket.onerror = function(event) {
        // console.log("WebSocket:发生错误 ");
        // console.log(event);
    };
    websocket.onclose = function(event) {
        // console.log("WebSocket:已关闭");
        // console.log(event);
    }
}